package com.zzyl.intercept;


import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.constant.UserCacheConstant;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //专门用来比较请求路径的类
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 判断请求是否是后端请求  如果不是则放行
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }
        //2.从请求头中获取token 然后判断token是否为空  为空则返回401
        String token = request.getHeader(Constants.USER_TOKEN);
        if(ObjectUtil.isEmpty(token)) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //3.解析token 然后判断是否为空 为空返回401
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if(ObjectUtil.isEmpty(claims)) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        String json = String.valueOf(claims.get("currentUser"));
        UserVo vo = JSONUtil.toBean(json, UserVo.class);
        //4.构建redis的key 然后从redis中获取当前用户的权限列表
        String key = UserCacheConstant.PUBLIC_ACCESS_URLS+vo.getId();
        String jsonList = stringRedisTemplate.opsForValue().get(key);
        List<String> urlList = JSONUtil.toList(jsonList,String.class);
        //5.获取当前请求的地址和请求方式
        String path = request.getMethod()+request.getRequestURI();

        //6.判断当前请求地址是否在权限列表中 如果不再则返回403
        Boolean flag = Boolean.FALSE;

        for(String url : urlList) {
            if(antPathMatcher.match(url, path)) {
                flag = Boolean.TRUE;
                break;
            }
        }
        if(flag){
            UserThreadLocal.set(vo.getId());
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }
}
